import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'umi';
import { Alert, Button, Space, Tag, Modal, notification, Row, Col, Checkbox, Dropdown } from 'antd'
import TableDataBlock from '@/components/TableDataBlock';
import PopImgShow from '@/components/PopImgShow';
import SearchCondition from '@/components/SearchCondition';
import AddPromoterShop from './components/addPromoterShop';
import SetPromoterTable from './components/setPromoterTable';
import { DownOutlined } from '@ant-design/icons';
import { goodsType_status, commission_type } from '@/common/contact'
import SelectPromoterGroup from '@/components/SelectPromoterGroup';
const PromoterShop = (props) => {
    const { loading, dispatch, list, zm } = props;
    const childRef = useRef();
    const [promoterGroupVisible, setPromoterVisible] = useState(false)
    const [promoterLevelList, setPromoterLevelList] = useState([])
    const [visiblePromoter, setVisiblePromoter] = useState(false)
    const [detaultShopList, setDetaultShopList] = useState([])
    const [proVisible, setProVisible] = useState(false)
    const [params, setSearchParams] = useState({})
    const [selectedRow, setSelectedRow] = useState({
        selectedRowKeys: [],
        type: 'checked',
        preserveSelectedRowKeys: true,
        onChange: (val, selectedRows) => {
            setSelectedRow({
                ...selectedRow,
                selectedRowKeys: val,
                rowKeyList: selectedRows
            });
        },

    });
    const fetchDetaultShop = () => {
        dispatch({
            type: 'promoter/fetchListPromoterGoodsIdList',
            callback: (e) => {

                setDetaultShopList(e)
            }
        })
    }
    const fetchLevelList = () => {
        dispatch({
            type: 'promoter/fetchPromoterSimpleLevelDetail',
            callback: (e) => {
                const { promoterLevelList } = e
                setPromoterLevelList(promoterLevelList)
            }
        })
    }
    const fakeSetGroupId = (payload) => {
        dispatch({
            type: 'promoter/fakeSetGoodsGroupIds',
            payload: payload,
            callback: (e) => {
                handleCallback()
                setSelectedRow({
                    ...selectedRow,
                    selectedRowKeys: [],
                })
            }
        })
    }
    useEffect(() => {
        childRef.current.initData();
    }, [params])
    useEffect(() => {
        fetchDetaultShop()
        fetchLevelList()
    }, [])
    // 搜索参数
    const searchItems = [

        {
            label: '商品类型',
            name: 'goodsType',
            type: 'select',
            select: goodsType_status
        },
        {
            label: '商品名称',
            name: 'keyword',
        },
        {
            label: '添加时间',
            type: 'rangePicker',
            name: 'createStartTime',
            end: 'createEndTime',
        },
        {
            label: '分组',
            name: 'groupId',
            type: 'promoterGroup',
        },
    ];
    // table 表头
    const getColumns = [
        {
            title: '商品信息',
            align: 'left',
            style: { textAlign: 'left' },
            width: 180,
            dataIndex: 'cover',
            render: (e, record) => {
                const { goodsName, price, priceType } = record
                return <Space>
                    <PopImgShow url={e}></PopImgShow>
                    <div>
                        <div> {goodsName}</div>
                        <div>{priceType === 'free' ? '--' : price}</div>
                    </div>
                </Space>
            }
        },

        {
            title: '商品类型 ',
            dataIndex: 'goodsType',
            render: (e) => {
                return goodsType_status[e]
            }
        },
        {
            title: '推广价',
            dataIndex: 'promoterPrice',
        },
        {
            title: '是否隐藏',
            dataIndex: 'hideFlag',
            render: (e) => {
                console.log(e, '1231233')
                if (e === '1') {
                    return '隐藏'
                }
                else {
                    return '显示'
                }

            }
        },
        {
            title: '分组',
            dataIndex: 'groupNames',
        },
        {
            title: '比例规则',
            dataIndex: 'commissionType',
            render: (e) => {
                return commission_type[e]
            }
        },
        {
            title: '商品佣金比例 ',
            dataIndex: 'commissionDescription',
            render: (e) => {
                if (e.length > 0) {
                    const list = JSON.parse(e)
                    let countList = list.reduce((item, index) => {
                        const { goodsCommissionPercentage } = index
                        let min = item[0]
                        let max = item[1]

                        min = goodsCommissionPercentage < min ? goodsCommissionPercentage : min === 0 ? goodsCommissionPercentage : min
                        max = goodsCommissionPercentage > max ? goodsCommissionPercentage : max
                        return [min, max]
                    }, [0, 0])
                    return <Dropdown
                        menu={{
                            items: list.map(item => {
                                const { levelName, goodsCommissionPercentage, inviteCommissionPercentage } = item
                                return {
                                    label: <Space>
                                        <div>{levelName}</div>
                                        <div>{goodsCommissionPercentage}%</div>
                                    </Space>
                                }
                            }),

                        }
                        }
                    >
                        <Space>
                            {countList[0] + '%' + '~' + countList[1] + '%'}
                            <DownOutlined />
                        </Space>
                    </Dropdown >
                }
                else {
                    return '--'
                }
            }
        },
        {
            title: '邀请人奖励比例 ',

            dataIndex: 'commissionDescription',
            render: (e) => {
                if (e.length > 0) {
                    const list = JSON.parse(e)
                    let countList = list.reduce((item, index) => {
                        const { inviteCommissionPercentage } = index
                        let min = item[0]
                        let max = item[1]

                        min = inviteCommissionPercentage < min ? inviteCommissionPercentage : min === 0 ? inviteCommissionPercentage : min
                        max = inviteCommissionPercentage > max ? inviteCommissionPercentage : max
                        return [min, max]
                    }, [0, 0])
                    return <Dropdown
                        menu={{
                            items: list.map(item => {
                                const { levelName, inviteCommissionPercentage, } = item
                                return {
                                    label: <Space>
                                        <div>{levelName}</div>
                                        <div>{inviteCommissionPercentage}%</div>
                                    </Space>
                                }
                            }),

                        }
                        }
                    >
                        <Space>
                            {countList[0] + '%' + '~' + countList[1] + '%'}
                            <DownOutlined />
                        </Space>
                    </Dropdown >
                }
                else {
                    return '--'
                }
            }
        },

        {
            title: '添加时间',
            dataIndex: 'createTime',
        },
        {
            title: '渠道',
            dataIndex: 'channel',
        },
        {
            type: 'handle',
            width: 200,
            dataIndex: 'id',
            render: (val, record) => [
                {
                    auth: true,
                    visible: record.priceType === 'money',
                    title: '修改比例',
                    click: () => {
                        const { commissionType, commissionDescription } = record
                        setProVisible({
                            show: true,
                            detail: [{ ...record, commissionDescription: commissionType === 'goods' ? commissionDescription ? JSON.parse(commissionDescription) : [] : '' }]
                        })
                    },
                },
                {
                    auth: true,
                    title: '移除',
                    click: () => {
                        Modal.error({
                            title: '确认移除商品',
                            content: `移除商品后，该组推广员将不可推广已选商品`,
                            okText: '确认',
                            onOk() {
                                dispatch({
                                    type: 'promoter/fakeRemovePromoterGoods',
                                    payload: { id: val },
                                    callback: () => {
                                        handleCallback()
                                    }
                                })
                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                        })
                    },
                },
            ],
        },
    ];
    const handleCallback = () => {
        childRef.current.fetchGetData();
    };
    console.log(detaultShopList, 'defa')

    return (

        <>
            <Row gutter={[36, 12]}>
                <Col span={24}>
                    <Space size={'large'}>
                        <Button type='primary' onClick={() => {
                            setVisiblePromoter({
                                show: true
                            })
                        }}>添加商品</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <div style={{ background: '#f5f5f5', padding: 24 }}>
                        <SearchCondition
                            handleSearch={(e) => {
                                setSearchParams(e);
                            }}
                            searchItems={searchItems}
                        ></SearchCondition>
                    </div>
                </Col>
                <Col span={24}>
                    <Space>
                        <Checkbox checked={selectedRow.selectedRowKeys.length === list.list.length} onChange={(e) => {
                            if (e.target.checked) {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: list.list.map(item => {
                                        return item.id.toString()
                                    }),
                                    rowKeyList: list.list
                                })
                            } else {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: [],
                                    rowKeyList: []
                                })
                            }

                        }}>当页全选</Checkbox>
                        <div>已选{selectedRow.selectedRowKeys.length} 条 </div>
                        <Button disabled={selectedRow.selectedRowKeys.length === 0} onClick={() => {
                            setProVisible({
                                show: true,
                                detail: selectedRow.rowKeyList.map(item => {
                                    const { commissionDescription, commissionType } = item
                                    return {
                                        ...item,
                                        commissionDescription: commissionType === 'goods' ? commissionDescription ? JSON.parse(commissionDescription) : [] : ''
                                    }
                                })
                            })
                        }}>修改比例</Button>
                        <Button disabled={selectedRow.selectedRowKeys.length === 0} onClick={() => {
                            Modal.error({
                                title: '确认移除商品',
                                content: `移除商品后，该组推广员将不可推广已选商品`,
                                okText: '确认',
                                onOk() {
                                    dispatch({
                                        type: 'promoter/fakeRemovePromoterGoods',
                                        payload: { idList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) }) },
                                        callback: () => {
                                            handleCallback()
                                            setSelectedRow({
                                                ...selectedRow,
                                                selectedRowKeys: [],

                                            })
                                        }
                                    })
                                },
                                onCancel() {
                                    console.log('Cancel');
                                },
                            })
                        }}>移除商品</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要绑定的商品`,
                                });
                            } else {
                                setPromoterVisible({
                                    show: true,
                                    detail: {},
                                    type: "all",
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量绑定分组</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <TableDataBlock
                        rowSelection={selectedRow}
                        cRef={childRef}
                        loading={loading}
                        params={params}
                        firstFetch={false}
                        columns={getColumns}
                        rowKey={(record) => `${record.id}`}
                        dispatchType="promoter/fetchListPromoterGoods"
                        {...list}
                    ></TableDataBlock>
                </Col>

                <AddPromoterShop getCheckboxProps={(
                    e
                ) => {

                    const flag = detaultShopList.reduce((item, val) => {
                        if (item) {
                            return item
                        }
                        return val == e.id
                    }, false)
                    console.log(flag)
                    return {
                        id: e.id,
                        disabled: flag

                    }
                }} handleCallback={handleCallback} visible={visiblePromoter} onClose={setVisiblePromoter}  ></AddPromoterShop>
                <SetPromoterTable cleanSelect={() => {
                    setSelectedRow({
                        ...selectedRow,
                        selectedRowKeys: [],
                        rowKeyList: []
                    })
                }} promoterLevelList={promoterLevelList} handleCallback={handleCallback} visible={proVisible} onClose={setProVisible}  ></SetPromoterTable>
                <SelectPromoterGroup onChange={(e = {}) => {
                    const { selectIdList } = promoterGroupVisible
                    const { groupIds } = e
                    fakeSetGroupId({
                        idList: selectIdList,
                        groupIds: groupIds.toString()
                    })
                }} visible={promoterGroupVisible} onClose={() => setPromoterVisible(false)}></SelectPromoterGroup>
            </Row>
        </>
    );
};

export default connect(({ promoter, loading }) => ({
    list: promoter.promoterGoodsList,
    loading: loading.models.promoter,
}))(PromoterShop);
